// chrome.storage.sync.set({alireviews: {}}, function() {});

createReviewButton();
function createReviewButton() {
    document.querySelectorAll("#transction-feedback > div.feedback-list-wrap > div.feedback-item").forEach(function(feedback) {
        let _id = ["EZ2DIY", Math.floor(Math.random() * 100000), Math.floor(Math.random() * 100000), Math.floor(Math.random() * 100000)].join("-")
        feedback.setAttribute("ez2diy", _id);

        let button = document.createElement("a");
        button.dataset.ez2diy = _id;
        button.innerText = "选择";
        button.classList.add("btn");
        button.classList.add("btn-primary");
        button.style.marginTop = "20px";
        button.style.padding = "5px 12px";
        button.style.fontSize = "0.8em";

        button.addEventListener('click', buttonClick);

        feedback.querySelector("div.fb-user-info").append(button);
    });
}

function buttonClick(e) {
    let target = e.target;
    if (target.getAttribute("disabled") === "disabled") {
        return;
    }
    let _id = target.dataset.ez2diy;
    let feedback = document.querySelector('[ez2diy="' + _id + '"');
    let feedback_id = feedback.querySelector("div.fb-main > div.f-content > dl > input.feedback-id").value;
    let data = {...getUserInfo(feedback), ...getContent(feedback), "img": getPhotos(feedback)}

    chrome.storage.sync.get({alireviews:{}}, function(items) {
        let item = items['alireviews'];
        if (item) {
            item[feedback_id] = data;
            chrome.storage.sync.set({alireviews: item}, function() {
                let button = document.querySelector("a[data-ez2diy='" + _id + "']");
                button.classList.add("disabled");
                button.setAttribute("disabled", "disabled");
                button.innerText = "已选择";
            });
        }
    });
}

function getUserInfo(feedback) {
    let userInfo = feedback.querySelector(".fb-user-info");
    let userName = userInfo.querySelector(".user-name").innerText;
    let country = userInfo.querySelector(".user-country").innerText;
    
    return {"username": userName, "country": country};
}

function getContent(feedback) {
    let contents = feedback.querySelectorAll("div.fb-main > div.f-content > dl > dt > span");

    return {"content": contents[0].innerText, "time": contents[1].innerText};
}

function getPhotos(feedback) {
    let photos = feedback.querySelector("div.fb-main > div.f-content > dl > dd");
    let src = "";
    photos && photos.querySelectorAll("img").forEach(function(img) {
        src += img.src + ",";
    });

    return src;
}

if (window == top) {
    console.log("TOP WINDOW");
    let id = "EZ2DIY-DATA-GRID-PANEL";
    if (!document.getElementById(id)) {
        let button = document.createElement("div");
        button.id = id;
        button.style.position = "fixed";
        button.style.bottom = '100px';
        button.style.right = '100px';
        button.style.zIndex = '1000';
        button.style.cursor = 'pointer';
        button.style.color = '#0461AE';
        button.style.padding = '12px';
        button.style.border = '1px solid #FC2424';
        //button.setAttribute('data-toggle',"modal");
        //button.setAttribute('data-target', "#ez2diy-modal");
        button.addEventListener('click', showDataGird);
        button.innerText = '查看数据';

        document.body.append(button);

        $(document.body).append([
            '<div class="modal fade" id="ez2diy-modal" tabindex="-1" aria-labelledby="ez2diyModalLabel" aria-hidden="true">',
            '  <div class="modal-dialog modal-xl">',
            '    <div class="modal-content">',
            '      <div class="modal-header">',
            '        <h5 class="modal-title" id="ez2diyModalLabel">Alireviews Grid</h5>',
            '        <button type="button" class="close" data-dismiss="modal" aria-label="Close">',
            '          <span aria-hidden="true">&times;</span>',
            '        </button>',
            '      </div>',
            '      <div class="modal-body" style="text-align: center;min-height: 60vh;">',
            '      </div>',
            '      <div class="modal-footer">',
            '        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>',
            '        <button id="ez2diy-download" href="#" class="btn btn-primary" download="alireview.csv">导出 CSV文件</button>',            
            '      </div>',
            '    </div>',
            '  </div>',
            '</div>'].join(""));
    }

}

function showDataGird() {
    console.log("showDateGird...");
    $('#ez2diy-modal .modal-body').html([
        '<div style="margin-top: 25vh;">',
        '<div class="spinner-grow spinner-grow-sm text-secondary" role="status" style="animation-delay: 0.15s;margin: 2px;"><span class="sr-only">Loading...</span></div>',
        '<div class="spinner-grow spinner-grow-sm text-secondary" role="status" style="animation-delay: 0.3s;margin: 2px;"><span class="sr-only">Loading...</span></div>',
        '<div class="spinner-grow spinner-grow-sm text-secondary" role="status" style="animation-delay: 0.45s;margin: 2px;"><span class="sr-only">Loading...</span></div>',
        '<div class="spinner-grow spinner-grow-sm text-secondary" role="status" style="animation-delay: 0.6s;margin: 2px;"><span class="sr-only">Loading...</span></div>',
        '<div class="spinner-grow spinner-grow-sm text-secondary" role="status" style="animation-delay: 0.7s;margin: 2px;"><span class="sr-only">Loading...</span></div>',
        '</div>'].join(""));
    $('#ez2diy-modal').modal({show: true});
    chrome.storage.sync.get({alireviews:{}}, function(items) {
        let item = items['alireviews'];

        $('#ez2diy-modal .modal-body').html(createDataGrid(item));
        document.getElementById("ez2diy-download").addEventListener("click", function() {
            let data = createDownloadButton(item);
            let a = document.createElement("a");
            a.href = data;
            a.download = "alireview.csv";
            document.body.append(a);
            a.click();
            setTimeout(function() {
                document.body.removeChild(a);
            }, 100);
        });

    });
}

function createDataGrid(items) {
    let html = ['<table class="table">',
    '<thead>',
    '    <tr>',
    '    <th scope="col">#</th>',
    '    <th scope="col">username</th>',
    '    <th scope="col">country</th>',
    '    <th scope="col">content</th>',
    '    <th scope="col">time</th>',
    '    <th scope="col">photos</th>',
    '    <th scope="col"></th>',
    '    </tr>',
    '</thead>',
    '<tbody id="data-body">'].join("");
    for (let i in items) {
        let data = items[i];
        if (!data) {
            continue;
        }

        html += "<tr>"
        html += '<td>' + i + '</td>';
        html += '<td>' + data.username + '</td>';
        html += '<td>' + data.country + '</td>';
        html += '<td>' + data.content + '</td>';
        html += '<td>' + data.time + '</td>';

        
        html += '<td>';
        if (data.img) {
            let photos = data.img.split(',');
            for (let j = 0; j < photos.length; j++) {
                if (photos) {
                    html += "<img src='" + photos[j] + "' style='max-width: 60px;max-height: 60px;margin-right: 5px;'/>"
                }
            }
        }

        html += '</td>';
        html += '<td><button type="button" class="btn btn-danger btn-sm" data-item-id="' + i + '" data-button-type="del">Del</button></td></tr>'
        
    }
    html += '</tbody></table>';
    return html;
}

function createDownloadButton(items) {
    let rows = [];
    rows.push(['Customer country','Customer name (male)','Customer name (female)','Rating','Content','Published date','Image Link (Optional)']);
    for (let i in items) {
        let data = items[i];
        if (!data) {
            continue;
        }
        let row = ["US"];
        row.push(US_MALE_NAMES[Math.floor(Math.random() * 1000000) % US_MALE_NAMES.length]);
        row.push(US_FEMALE_NAMES[Math.floor(Math.random() * 1000000) % US_FEMALE_NAMES.length]);
        row.push(randomRating());
        row.push(getCSVText(data.content));
        row.push(randomDate());

        rows.push(row);
    }

    return "data:application/csv," + encodeURIComponent(rows.join("\r\n"));
}

function randomRating() {
    let rating = 5;
    if (Math.random() * 100 > 70) {
        rating -= 1;
    }

    if (Math.random() * 100 > 80) {
        rating -= 1;
    }

    return rating;
}

function randomDate() {
    let subDay = Math.floor(Math.random() * 100) % 10;
    if (Math.random() * 100 > 30) {
        subDay += Math.floor(Math.random() * 100) % 20;
    }
    if (Math.random() * 100 > 90) {
        subDay += Math.floor(Math.random() * 100) % 30;
    }

    return dayjs().subtract(subDay, 'day').format('YYYY-MM-DD');
}

function getCSVText(str) {
    return '"' + str + '"';
}

console.log("Content Script Init!")